<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // let obj={date:'520'};
        // let val = obj.date; 
        // Object.defineProperty(obj,'date',{
        //     get(){//获取date 对象触发的方法
        //        //return obj.date;//不能这么写,会造成递归
        //        console.log('触发了get的调用');
        //        return val;
        //     },
        //     set(newVal){
        //         if(newVal!=val){
        //             console.log('出发了set的调用');
        //             //去修改dom 
        //             val=newVal;
        //         }
        //     }
        // })
        // obj.date;
        // obj.date='521';


        //实际情况中，对象也可能嵌套对象
        let data = {
            date: '520',
            action: {
                action1: '买花',
                action2: '买礼物',
                action3:{
                    money:1314,
                    mood:'sad'
                }

            },
            age: 20
        }

        //给对象的每一个元素都绑定，get set
        class Observer {

            constructor(obj) {
                this.handleObj(obj)
            }

            handleObj(obj) {
                if (obj && typeof obj == 'object') {
                    for (let key in obj) {
                        this.addGetSet(obj, key, obj[key]);
                    }
                }
            }

            addGetSet(obj, attr, val) {
                this.handleObj(val);//如果这个值，不是object，如果是object
                Object.defineProperty(obj, attr, {
                    get() {
                        console.log('observer 触发 get',val);
                        return val;
                    },
                    set(newVal) {
                        if (newVal != val) {
                            console.log('observer 触发 set',newVal);
                            // 做些 dom操作，可以找 dom中值，把它变更
                            val = newVal
                        }
                    }
                })
            }

        }

        new Observer(data);
        data.date;
        data.age;
        data.date = '521';
        data.age = 22

        data.action.action1
        data.action.action1='买菜花';

        data.action.action3.money=200;
        data.action.action3.mood='happy';


    </script>
</body>

</html>